<template>
  <div class="app-container">
    <el-card title="预警分类树">
      <el-tree
        :data="categoryTree"
        :props="treeProps"
        node-key="id"
        default-expand-all
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span v-if="!data.isProduct">{{ data.categoryName }}</span>
            <div v-else class="product-node">
              <span class="product-name">{{ data.categoryName }}</span>
              <span class="product-sku">SKU: {{ data.sku }}</span>
              <span class="product-id">商品ID: {{ data.productId }}</span>
              <span class="product-quantity">
                    库存: {{ data.quantity !== null ? data.quantity : '--' }}/{{ data.warningThreshold }}
                    <span v-if="data.quantity !== null">
  ({{ Math.round((data.quantity / data.warningThreshold) * 100) }}%)
  <span v-if="(data.quantity / data.warningThreshold) * 100 > 95 && data.alertStatus !== 1"
        class="warning-text">⚠️ 建议预警</span>
</span>
                  </span>
              <span class="product-status"
                    :class="{'status-warning': data.alertStatus === 1, 'status-normal': data.alertStatus === 0}"
                    @click="handleStatusClick(data)">
                  {{ data.alertStatus === 1 ? '⚠️ 库存预警' : '✅ 正常' }}
                </span>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <div class="threshold-update">
      <el-button type="primary" icon="el-icon-edit" @click="dialogVisible = true">
        修改商品阈值
      </el-button>
      <el-button type="success" icon="el-icon-download" @click="handleExport">
        导出Excel
      </el-button>

      <el-dialog title="更新商品阈值" :visible.sync="dialogVisible" width="30%">
        <el-form :model="thresholdForm" :rules="thresholdRules" ref="thresholdForm">
          <el-form-item label="商品ID" prop="productId">
            <el-input v-model="thresholdForm.productId" placeholder="请输入商品ID"></el-input>
          </el-form-item>
          <el-form-item label="预警阈值" prop="warningThreshold">
            <el-input v-model.number="thresholdForm.warningThreshold" placeholder="请输入预警阈值"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateThreshold">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import warn from '@/api/warn/warn'

export default {
  name: 'WarnIndex',
  data() {
    return {
      categoryTree: [],
      dialogVisible: false,
      thresholdForm: {
        productId: '',
        warningThreshold: null
      },
      thresholdRules: {
        productId: [
          { required: true, message: '请输入商品ID', trigger: 'blur' }
        ],
        warningThreshold: [
          { required: true, message: '请输入预警阈值', trigger: 'blur' },
          { type: 'number', message: '预警阈值必须为数字', trigger: 'blur' }
        ]
      },
      treeProps: {
        label: 'categoryName',
        children: 'children'
      }
    }
  },
  created() {
    this.loadCategoryTree()
  },
  methods: {
    handleUpdateThreshold() {
      this.$refs.thresholdForm.validate((valid) => {
        if (valid) {
          warn.updateThreshold(this.thresholdForm)
            .then(response => {
              this.$message.success('阈值更新成功')
              this.dialogVisible = false
              this.loadCategoryTree() // 重新加载数据
            })
            .catch(error => {
              this.$message.error('阈值更新失败: ' + error.message)
            })
        }
      })
    },
    handleStatusClick(product) {
      console.log('点击事件触发，产品数据:', product)
      warn.updateProductStatus(product)
        .then(response => {
          this.$message.success('状态更新成功')
        })
        .catch(error => {
          this.$message.error('状态更新失败: ' + error.message)
        })
    },
    loadCategoryTree() {
      warn.getCategoryTree().then(response => {
        this.categoryTree = this.transformData(response.data)
      })
    },
    transformData(nodes) {
      return nodes.map(node => {
        // 为分类节点添加唯一标识
        const transformedNode = {
          ...node,
          id: node.categoryId
        };

        // 将商品转换为树形节点
        const productNodes = node.products.map(product => ({
          id: `product_${product.productId}`, // 商品节点ID添加前缀避免冲突
          categoryName: product.productName,
          sku: product.sku,
          productId: product.productId,
          alertStatus: product.alertStatus,
          warningThreshold: product.warningThreshold,
          quantity: product.quantity,
          children: [],
          isProduct: true
        }));

        // 合并子分类和商品节点
        transformedNode.children = [
          ...(node.children ? this.transformData(node.children) : []),
          ...productNodes
        ];
        return transformedNode;
      });
    },
    handleNodeClick(data) {
      this.$message.info(`点击了节点: ${data.categoryName}`)
      // 可以添加节点点击事件逻辑，如查看该分类下的预警信息
    },
    // 导出excel的方法
    handleExport() {
      console.log('开始导出Excel...')
      warn.exportProducts()
        .then(response => {
          console.log('导出响应:', response)
          console.log('响应数据类型:', typeof response)
          console.log('响应数据大小:', response.size || response.length)

          // 验证数据是否为Blob类型
          if (!(response instanceof Blob)) {
            console.error('响应数据不是Blob类型:', response)
            this.$message.error('导出失败：数据格式错误')
            return
          }

          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;

          // 日期格式化逻辑
          const date = new Date();
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          const day = date.getDate();
          const pad = (num) => num < 10 ? '0' + num : num;
          const fileName = `商品数据_${year}-${pad(month)}-${pad(day)}.xlsx`;
          a.download = fileName;
          console.log('准备下载文件:', fileName)

          a.click();
          URL.revokeObjectURL(url);
          this.$message.success('导出成功！')
        })
        .catch(error => {
          console.error('导出错误详情:', error)
          this.$message.error(`导出失败：${error.message || '未知错误'}`);
        });
    }
  }
}
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
}

.product-node {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  width: 100%;
  padding: 4px 0;
}

.product-name {
  font-weight: 500;
  min-width: 120px;
}

.product-sku,
.product-id,
.product-quantity {
  color: #606266;
  font-size: 12px;
  white-space: nowrap;
}

.product-status {
  margin-left: auto;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-warning {
  background: #fff2e8;
  color: #e6a23c;
}

.status-normal {
  background: #f0f9eb;
  color: #67c23a;
}

.warning-text {
  color: red;
  margin-left: 5px;
  font-weight: bold;
}

.threshold-update {
  margin-top: 20px;
  text-align: right;
}
</style>
